<script lang="ts" setup>
import { ref, reactive, computed } from "vue";
import type { FormRules, FormInstance } from "element-plus";
import type { FlowNodeInterface } from "@/components/FlowNode/type";
import { cloneDeep, flattenDeep } from "lodash-es";
import { v4 as uuidv4 } from "uuid";
import "element-plus/es/components/message/style/css";
import { ElMessage } from "element-plus";
import { traverseMultiDimArray } from "@/utils/utils";

let stageForm = reactive<FlowNodeInterface>({
    name: "",
    prevStage: [],
    nextStage: [],
    isStarter: false,
    startDays: "",
    endDays: "",
    level: 0,
    minus: "58px",
    mul: 1,
    type: "node",
});

const rules = reactive<FormRules<FlowNodeInterface>>({
    name: [{ required: true, message: "请输入阶段名称" }],
    startDays: [
        {
            required: true,
            validator: (rule: any, value: any, callback: any) => {
                if (!stageForm.startDays || !stageForm.endDays) {
                    callback(new Error("请输入标准住院日"));
                } else if (
                    stageForm.startDays &&
                    stageForm.endDays &&
                    stageForm.startDays >= stageForm.endDays
                ) {
                    callback(new Error("请输入正确的天数范围"));
                } else {
                    callback();
                }
            },
            trigger: "change",
        },
    ],
    endDays: [
        {
            required: true,
            validator: (rule: any, value: any, callback: any) => {
                if (!stageForm.startDays || !stageForm.endDays) {
                    callback(new Error("请输入标准住院日"));
                } else if (
                    stageForm.startDays &&
                    stageForm.endDays &&
                    stageForm.startDays >= stageForm.endDays
                ) {
                    callback(new Error("请输入正确的天数范围"));
                } else {
                    callback();
                }
            },
            trigger: "change",
        },
    ],
});

// const stageData: FlowNodeInterface[][] = [
//     [
//         {
//             id: "stage-1-1",
//             name: "入院第一天",
//             prevStage: null,
//             nextStage: ["stage-2-1"],
//             dateRange: "(1-1天)",
//         },
//     ],
//     [
//         {
//             id: "stage-2-1",
//             name: "住院第二天",
//             prevStage: ["stage-0-0"],
//             nextStage: ["stage-3-1", "stage-3-2"],
//             dateRange: "(2-2天)",
//         },
//     ],
//     [
//         {
//             id: "stage-3-1",
//             name: "术前",
//             prevStage: "stage-2-1",
//             nextStage: null,
//             dateRange: "(3-5天)",
//         },
//         {
//             id: "stage-3-2",
//             name: "住院第三-六天",
//             prevStage: "stage-2-1",
//             nextStage: null,
//             dateRange: "(3-6天)",
//         },
//     ],
// ];

const stageData = ref<FlowNodeInterface[][]>([
    [
        {
            id: "111",
            name: "入院第一天",
            prevStage: [],
            nextStage: [],
            isStarter: true,
            startDays: "1",
            endDays: "2",
            level: 1,
            minus: "58px",
            mul: 1,
            type: "node",
        },
    ],
]);

// reference
const stageFormRef = ref<FormInstance>();

// computed
const nodeOptions = computed(
    () => flattenDeep(stageData.value) as FlowNodeInterface[],
);

const starterDisabled = computed(() => stageData.value.length !== 0);

// 新增按钮事件
const add = async (formEl: FormInstance | undefined) => {
    if (!formEl) {
        return;
    }
    await formEl.validate((valid, fields) => {
        if (valid) {
            const isBlank = stageData.value.length === 0;
            if (!stageForm.isStarter && isBlank) {
                return ElMessage.warning({
                    message: "还没有起始流程，请勾选起点",
                    type: "warning",
                });
            }
            const nodeData = cloneDeep(stageForm) as FlowNodeInterface;
            nodeData.id = uuidv4();
            // 如果没有起始节点
            if (isBlank) {
                stageData.value?.push([nodeData]);
                formEl.resetFields();
            } else {
                traverseMultiDimArray(
                    stageData.value,
                    (item: FlowNodeInterface, index) => {
                        if (nodeData.prevStage.indexOf(item.id) !== -1) {
                            item.nextStage.push(nodeData.id);
                            const { level } = item;
                            nodeData.level = level + 1;
                            debugger;
                            const prevLen = stageData.value[level - 1].length;
                            if (!stageData.value[level]) {
                                nodeData.mul = prevLen - 1 ? prevLen - 1 : 1;
                                if (prevLen > 1) {
                                    nodeData.minus = "8px";
                                }
                                stageData.value?.push([nodeData]);
                            } else {
                                const curLen =
                                    stageData.value[level].length + 1;
                                nodeData.mul =
                                    prevLen - curLen ? prevLen - curLen : 1;
                                if (prevLen > 1) {
                                    nodeData.minus = "8px";
                                }
                                stageData.value[level]?.push(nodeData);
                            }
                        }
                    },
                );
            }
        } else {
            console.log("新增失败", fields);
        }
    });
};

const handleChange = () => {
    console.log("handle change");
};
</script>

<template>
    <div class="flex items-center p-2">
        <div class="flex-1">
            <FlowWrap :stageData="stageData" />
        </div>
        <el-form
            class="w-300px"
            ref="stageFormRef"
            :model="stageForm"
            :rules="rules"
            label-width="auto"
        >
            <el-form-item label="阶段名称" prop="name">
                <el-input v-model="stageForm.name" />
            </el-form-item>
            <el-form-item label="上一阶段">
                <div class="flex gap-10px w-full">
                    <el-form-item class="flex-1" prop="prevStage">
                        <el-select
                            v-model="stageForm.prevStage"
                            multiple
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="nodeOption in nodeOptions"
                                :key="nodeOption.id"
                                :value="nodeOption.id"
                                :label="nodeOption.name"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="isStarter">
                        <el-checkbox
                            v-model="stageForm.isStarter"
                            :disabled="starterDisabled"
                            label="起点"
                        />
                    </el-form-item>
                </div>
            </el-form-item>
            <el-form-item label="阶段时间(天)">
                <div class="flex items-center">
                    <el-form-item prop="startDays">
                        <el-input
                            v-model="stageForm.startDays"
                            @change="handleChange"
                        />
                    </el-form-item>
                    <span> &nbsp;-&nbsp; </span>
                    <el-form-item prop="endDays">
                        <el-input
                            v-model="stageForm.endDays"
                            @change="handleChange"
                        />
                    </el-form-item>
                </div>
            </el-form-item>
            <el-form-item>
                <div class="w-full flex justify-center">
                    <el-button type="default">重置</el-button>
                    <el-button type="danger">确认修改</el-button>
                    <el-button type="primary" @click="add(stageFormRef)"
                        >新增</el-button
                    >
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>
